package com.wantup.demo01;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Zhaoluowei
 * @version 1.0
 * @date 2019/6/25 17:36
 * <p>
 * 生产者 消费者
 * 产生的问题：
 */
public class TestProductAndConsumerByLock {

    public static void main(String[] args) {
        Clerk02 clerk = new Clerk02();

        Product02 product = new Product02(clerk);
        Consumer02 consumer = new Consumer02(clerk);

        /**
         * 会造成 有的线程没办法唤醒。
         */
        new Thread(product, "生产者 A ").start();
        new Thread(consumer, "消费者 B ").start();
        new Thread(product, "生产者 C ").start();
        new Thread(consumer, "消费者 D ").start();


    }

}


class Clerk02 {
    //这个商品是共享数据
    private int product = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    //进货
    public void getProduct() {

        try {
            lock.lock();
            while (product >= 10) {
                System.out.println("产品已满");
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }// else {
            System.out.println(Thread.currentThread().getName() + " : " + ++product);
            condition.signalAll();
//        }

        } finally {
            lock.unlock();
        }

    }

    //卖货
    public void sale() {
        try {
            lock.lock();
            while (product <= 0) {
                System.out.println("缺货");
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + " : " + --product);
            condition.signalAll();


        } finally {
            lock.unlock();
        }

    }


}

//生产者
class Product02 implements Runnable {

    private Clerk02 clerk;

    public Product02() {
    }

    public Product02(Clerk02 clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {

        for (int i = 0; i < 20; i++) {

            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            clerk.getProduct();
        }

    }
}


class Consumer02 implements Runnable {
    private Clerk02 clerk;

    public Consumer02() {
    }

    public Consumer02(Clerk02 clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            clerk.sale();
        }
    }
}






